/**
 * @file    Expression classname is undefined on line 2, column 15 in Templates/Classes/Class.java.
 * @author  Haseeb Yousaf
 * @see     LICENSE (MIT style license file)
 * @version 1.0
 * @date    Nov 14, 2011 12:52:52 PM
 */
package carrello.impl.controller.user;

import java.util.logging.Logger;
import java.util.logging.Level;
import java.security.NoSuchAlgorithmException;
import java.math.BigInteger;
import org.hibernate.Session;
import java.security.MessageDigest;
import carrello.model.entities.User;
import static carrello.util.EntityManagerUtil.getEntityManager;
import static carrello.util.hiberutil.buildSessionFactory;
public class SignUpCTRL {
    
    // This method generates the md5 hash of any string passed to it
    private static String getMD5Hash ( String password ) 
    {
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.reset();
            m.update(password.getBytes());
            byte[] digest = m.digest();
            BigInteger bigInt = new BigInteger(1,digest);
            String hashtext = bigInt.toString(16);
            // Now we need to zero pad it if you actually want the full 32 chars.
            while(hashtext.length() < 32 ){
              hashtext = "0"+hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(SignUpCTRL.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }    
    public static boolean verify(String username)
    {
        User user = (User) User.getUserByUserName(username);
        return (user == null);
    } // 
    
    public static void addUser(String username, String password, String email, String firstName, String lastName, String address)
    {
        String md5 = getMD5Hash(password);
//        getEntityManager().beginUnitOfWork();
//        getEntityManager().store(user);
//        getEntityManager().endUnitOfWork();
        Session ses = buildSessionFactory().openSession();
        User user  = new User(username, firstName, lastName, md5, email ,address, "user");
        System.out.println("session created" + ses);
        ses.beginTransaction();
        ses.save(user);
        ses.getTransaction().commit();
    }
}
